import styles from '../styles.less';
import {Space, Table, Tag, Pagination, Image, Popover, Modal, Dropdown} from 'antd';
import {useCallback, useEffect} from 'react';
import {connect, useAccess} from 'umi';
import Opera from './Opera'
import {DownOutlined, ExclamationCircleFilled} from "@ant-design/icons";

const DataTable = (props) => {

  const {dispatch, loading, dataTable, submitting} = props;
  const {setBalances, setRechargeForm, setTags, setDataForm, setDetail, tablePayload, setTablePayload} = props.data;
  const access = useAccess();

  /* 获取列表 */
  const fetchList = useCallback((payload) => {
    dispatch({
      type: 'PVipUser/fetchList',
      payload: payload,
    });
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    fetchList(tablePayload);
  }, [fetchList, tablePayload]);

  /* 充值 */
  function recharge(e, record) {
    e.preventDefault();
    setRechargeForm({
      visible: true,
      title: '充值操作',
      data: record,
    });
    return false;
  }

  /* 余额流水 */
  function balances(record) {
    setBalances({
      visible: true,
      title: '余额流水',
      data: record,
    });
  }

  /* 编辑 */
  function edit(record) {
    setDataForm({
      visible: true,
      title: '编辑操作',
      data: record,
    });
  }

  /* 查看详情 */
  function detail(e, record) {
    e.preventDefault();
    setDetail({
      visible: true,
      title: '查看详情',
      data: record,
    });
    return false;
  }

  /* 停用/启用 */
  function status(record) {
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: record.status === 1 ? '是否确定停用？' : '是否确定启用',
        onOk() {
          dispatch({
            type: 'PVipUser/status',
            payload: record.id,
            callback: () => {
              setTablePayload({...tablePayload, pageNum: 1});
            },
          });
        },
      });
    }
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      fixed: 'left',
      render: ({}, {}, index) => (
        <span>
          {(tablePayload.pageNum - 1) * tablePayload.pageSize + index + 1}
        </span>
      ),
    },
    {
      title: '用户头像',
      dataIndex: 'avatar',
      align: 'center',
      width: 100,
      ellipsis: true,
      render: (_, record) => {
        return (
          <Image
            width={40} height={40} src={record.avatar}
            fallback=""
          />
        );
      },
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      align: 'center',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        return (
          <span>{record.mobile ? record.mobile : '-'}</span>
        );
      },
    },
    {
      title: '用户名称',
      dataIndex: 'name',
      align: 'center',
      ellipsis: true,
      width: 180,
      render: (_, record) => {
        return (
          <span>{record.name ? record.name : '-'}</span>
        );
      },
    },
    {
      title: '用户编号',
      dataIndex: 'code',
      align: 'center',
      width: 120,
      ellipsis: true,
      render: (_, record) => {
        return (
          <span>{record.code ? record.code : '-'}</span>
        );
      },
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      align: 'center',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        return (
          <span>{record.realName ? record.realName : '-'}</span>
        );
      },
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      align: 'center',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        return (
          <Tag color={record.status === 1 ? 'geekblue' : 'volcano'}>
            {record.status === 1 ? '正常' : '停用'}
          </Tag>
        );
      },
    },
    {
      title: '当前余额',
      dataIndex: 'balanceAmount',
      align: 'center',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        return (
          <span style={{color: 'green'}}>{(record.balanceAmount / 100).toFixed(2)}</span>
        );
      },
    },
    {
      title: '当前积分',
      dataIndex: 'pointAmount',
      align: 'center',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        return (
          <span style={{color: 'green'}}>{record.pointAmount}</span>
        );
      },
    },
    {
      title: '用户标签',
      dataIndex: 'userInfoTagLinkList',
      align: 'center',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        if (record.userInfoTagLinkList.length <= 0) {
          return <span style={{color: '#1d39c4'}}>{record.userInfoTagLinkList.length}</span>;
        }

        const content = (
          <div>
            {record.userInfoTagLinkList.map(d => {
              return (<div key={d}>{d.tagName}</div>);
            })}
          </div>
        );
        return (
          <Popover content={content}>
            <span style={{color: '#1d39c4'}}>{record.userInfoTagLinkList.length}</span>
          </Popover>
        );
      },
    },
    {
      title: '性别',
      dataIndex: 'type',
      align: 'center',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        let genderName;
        switch (record.gender) {
          case 0:
            genderName = '未知';
            break;
          case 1:
            genderName = '男';
            break;
          case 2:
            genderName = '女';
            break;
        }
        return (
          <span>{genderName ? genderName : '-'}</span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      ellipsis: true,
      width: 160,
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      width: 140,
      fixed: 'right',
      render: (_, record) => {
        let items = [];
        if (access?.user_info_edit) {
          items = [...items, {
            key: 'edit',
            label: '编辑',
            onClick: () => edit(record)
          }];
        }
        if (access?.user_info_status) {
          items = [...items, {
            key: 'status',
            label: record.status === 0 ? '启用' : '停用',
            onClick: () => status(record)
          }];
        }
        if (access?.user_balanceLog_list) {
          items = [...items, {
            key: 'balances',
            label: '余额流水',
            onClick: () => balances(record)
          }];
        }

        return (
          <div style={{display: 'flex', textAlign: 'center', justifyContent: 'center'}}>
            <Space size='small'>
              <a onClick={e => detail(e, record)}>详情</a>
            </Space>
            {access?.user_balance_recharge && (
              <Space size='small' style={{marginLeft: 6}}>
                <a onClick={e => recharge(e, record)}>充值</a>
              </Space>
            )}
            {(items.length > 0) && (
              <div style={{marginLeft: 6}}>
                <Dropdown arrow menu={{items}}>
                  <a onClick={(e) => e.preventDefault()}>
                    更多<DownOutlined/>
                  </a>
                </Dropdown>
              </div>
            )}
          </div>
        )
      },
    },
  ];

  return (
    <>
      <div className={styles.myDataTable}>
        <Opera data={{setTags}}/>
        <Table
          loading={loading}
          className={styles.myTable} bordered={false} size={'middle'} columns={columns}
          dataSource={dataTable.list} rowKey={'id'}
          pagination={false} scroll={{y: '100%'}}
        />
      </div>
      <Pagination
        pageSize={tablePayload.pageSize} current={tablePayload.pageNum} total={dataTable.total}
        className={styles.myPagination} size={'default'} hideOnSinglePage={false}
        showTotal={(total) => {
          return `共 ${total} 条记录`;
        }}
        pageSizeOptions={[15, 30, 60, 120]}
        showSizeChanger showQuickJumper={true}
        onChange={(page, pageSize) => {
          setTablePayload({...tablePayload, pageNum: page, pageSize: pageSize});
        }}
      />
    </>
  );
};

export default connect(({loading, PVipUser}) => {
  return {
    loading: loading.effects['PVipUser/fetchList'],
    dataTable: PVipUser.dataTable,
    submitting: loading.effects['PVipUser/status'],
  };
})(DataTable);
